package com.linkai.序列化;

import java.io.*;

/**
 * @Description: 序列化算法存在的问题
 * @Author: 林凯
 * @Date: 2021/10/21 23:43
 */
public class Test02 {

    public static void WriteObject() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.txt"));
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.txt"));

            // 第一次序列化 person
            Person02 person = new Person02("JackLin", 21);
            oos.writeObject(person);

            // 修改name
            person.setName("林千辰");
            person.setAge(18);

            // 第2次序列化 person
            oos.writeObject(person);

            // 依次反序列化出 p1,p2
            Person02 p1 = (Person02) ois.readObject();
            Person02 p2 = (Person02) ois.readObject();
            System.out.println(p1);
            System.out.println(p2);
            /*
                Person{name='JackLin', age=21}
                Person{name='JackLin', age=21}
                结论：如果序列化一个可变对象（对象内的内容可更改）后，更改了对象内容，再次序列化，
                     并不会再次将此对象转换为字节序列，而只是保存序列化编号。
            * */

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        WriteObject();
    }


}
class Person02 implements Serializable {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Person02() {
    }

    public Person02(String name, int age) {
        System.out.println("调用了有参构造");
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

